<?php
class M_qin_users extends Cemvc_Db_MysqlDb{
  public $PrimaryKey='id';
  /*CEPHP会在要需要时查询主键，但主动设置主键可以使程序执行更快*/

  public function __construct()
  {
    parent::__construct();
  }

  /* insert a user when register */
  public function add($array)
  {
    $param = array();
    if (isset($array["username"]))
      $param["username"] = addslashes($array["username"]);
    if (isset($array["first_name"]))
      $param["first_name"] = addslashes($array["first_name"]);
    if (isset($array["name"]))
      $param["name"] = addslashes($array["name"]);
    if (isset($array["symbol"]))
      $param["symbol"] = addslashes($array["symbol"]);
    if (isset($array["title"]))
      $param["title"] = addslashes($array["title"]);
    if(isset($array["gender"]))
      $param["gender"] = addslashes($array["gender"]);
    if(isset($array["region_code"]))
      $param["region_code"] = addslashes($array["region_code"]);
    if(isset($array["password"]))
      $param["password"] = md5($array["password"]);
    if(isset($array["qq_open_id"]))
      $param["qq_open_id"] = addslashes($array["qq_open_id"]);
    if(isset($array["day_of_birth"]))
      $param["day_of_birth"] = addslashes($array["day_of_birth"]);
    if(isset($array["creator"]))
      $param["creator"] = addslashes($array["creator"]);
    if(isset($array["open"]))
      $param["open"] = addslashes($array["open"]);
    if(isset($array["signature"]))
      $param["signature"] = addslashes($array["signature"]);
    if(isset($array["oauth"]))
      $param["oauth"] = addslashes($array["oauth"]);
    if(isset($array["openid"]))
      $param["openid"] = addslashes($array["openid"]);
    if(isset($array["figureurl"]))
      $param["figureurl"] = addslashes($array["figureurl"]);

    $param["realname"] = addslashes($array["first_name"].$array["name"]);

    $res = $this->insert($param);

    $this->clear_cache($res["last_insert_id()"]);

    $user = $this->get($res["last_insert_id()"]);
    /* some else create me */
    if (isset($user["creator"]) && $user["creator"])
      {
	$author_id = $user["creator"];
	$author_name = $_SESSION["realname"];
      }
    /* I register, I am the creator */
    else
      {
	$author_id = $user["id"];
	$author_name = $user["realname"];
      }
    /* add to operate history */
    $history = new M_qin_history();
    $history->add(array("content_type" => CONTENT_TYPE_USER,
			"content_id"   => $user["id"],
			"content"      => base64_encode(serialize($user)),
			"operate_type" => OPERATE_TYPE_ADD,
			"author_id"    => $author_id,
			"author_name"  => $author_name));

    return $user;
  }
  public function edit($id, $array)
  {
    $this->where(array("id = $id"))->update($array);    
    $this->clear_cache($id);

    $user = $this->get($id);

    /* add to operate history */
    $history = new M_qin_history();
    $history->add(array("content_type" => CONTENT_TYPE_USER,
			"content_id"   => $id,
			"content"      => base64_encode(serialize($user)),
			"operate_type" => OPERATE_TYPE_EDIT,
			"author_id"    => $_SESSION["id"],
			"author_name"  => $_SESSION["realname"]));

    return $user;
  }

  public function delete($id)
  {
    $this->where(array("id = $id"))->update(array("state"=>RESOURCE_STATE_DELETED));
    $this->clear_cache($id);

    $user = $this->get($id);

    /* add to operate history */
    $history = new M_qin_history();
    $history->add(array("content_type" => CONTENT_TYPE_USER,
			"content_id"   => $id,
			"content"      => base64_encode(serialize($user)),
			"operate_type" => OPERATE_TYPE_DELETE,
			"author_id"    => $_SESSION["id"],
			"author_name"  => $_SESSION["realname"]));
    return $user;
  }
  public function restore($id)
  {
    /* update data */
    $this->where("id = $id")->update(array("state"=>RESOURCE_STATE_INIT));

    /* clear cache */
    $this->clear_cache($id);

    $user = $this->get($id);

    /* add to operate history */
    $history = new M_qin_history();
    $history->add(array("content_type" => CONTENT_TYPE_USER,
			"content_id"   => $id,
			"content"      => base64_encode(serialize($user)),
			"operate_type" => OPERATE_TYPE_RESTORE,
			"author_id"    => $_SESSION["id"],
			"author_name"  => $_SESSION["realname"]));
    return $user;
  }

  public function get_user_with_username($username)
  {
    return $this->where("username = '$username'")->fetchOne();
  }
  public function get_user_with_qqopenid($qq_open_id)
  {
    return $this->where("qq_open_id = '$qq_open_id'")->fetchOne();
  }
  public function get_user_with_openid($oauth, $openid)
  {
    return $this->where(array("oauth = '$oauth'", "openid = '$openid'"))->fetchOne();
  }

  public function get_users_with_surname($surname)
  {
    return $this->setField(array("id", "gender", "realname", "region_code", "figureurl"))
      ->where(array("first_name = '".addslashes($surname)."'", "state = '".RESOURCE_STATE_INIT."'", "open = '".FAMILY_OPEN_PUBLIC."'"))
      ->limit(USERS_PER_SURNAME_PAGE)
	    ->fetchAll();
  }

  /* used only in login process */
  public function get_user($username, $passwd)
  {
    return $this->where(array("username = '".addslashes($username)."'", "password = '".md5($passwd)."'", "state = '".RESOURCE_STATE_INIT."'"))->fetchOne();
  }

  public function get($id)
  {
    return $this->where(array("id = $id"))->fetchOne();
  }

  public function get_users(array $where=null)
  {
	  if ($where)
		  return $this->where($where)->fetchAll();
	  else
		  return $this->fetchAll();
  }

  /* you can find all open state users and see their base info
   * but you can see only the public user's event and photo
   * */
  public function find_users($name, $region)//, $open=FAMILY_OPEN_PUBLIC)
  {
    $matches = array();
    $matches[] = "realname like '%".addslashes($name)."%' ";
    /* $matches[] = "state = '".RESOURCE_STATE_INIT."'"; */
    /* $matches[] = "open = '${open}'"; */

    if ($region)
      {
	$region = (int)$region;
	$province = (int)$region / 10000;
	$city = (int)$region / 100;
    
	if ($region % 10000 == 0) /* only province select */
	  $str = "region_code >= ".($province*10000)." and region_code < ".(($province+1)*10000);
	else if ($region % 100 == 0) /* city select */
	  $str = "region_code > ".($city*100)." and region_code < ".(($city+1)*100);
	else
	  $str = "region_code = $region";
	$matches[] = $str;
      }

    return $this->where($matches)->limit(ITEM_COUNT_PER_PAGE)->fetchAll();

  }
  public function clear_cache($user_id)
  {
    $user = $this->get($user_id);
    M_Tools::del_cache($this->LastQueryString);	

    $this->get_user_with_username($user["username"]);
    M_Tools::del_cache($this->LastQueryString);	

    $this->get_user_with_qqopenid($user["qq_open_id"]);
    M_Tools::del_cache($this->LastQueryString);	

    $history = new M_qin_history();
    $history->get_history_with_content(CONTENT_TYPE_USER, $user_id);
    M_Tools::del_cache($history->LastQueryString);
  }

  /* get surname of all the users */
  public function get_surnames()
  {
    $sql = "select distinct(first_name) as surname, count(id) as num from users where state = '".RESOURCE_STATE_INIT."' and open = '".FAMILY_OPEN_PUBLIC."' group by surname order by num desc;";
    $this->mysqlQuery($sql);
    return $this->query()->fetchAll();
  }

  public function get_latest_users($num)
  {
    return $this->setField(array("id", "realname", "figureurl", "gender", "region_code", "ts_created"))
      ->orderBy("id desc")
      ->limit($num)
      ->fetchAll();
  }
  public function get_hot_people($open='public')
  {
    return $this->setField(array("id", "realname", "figureurl", "gender"))
      ->where("figureurl!=''", "open = '".FAMILY_OPEN_PUBLIC."'", "state = '".RESOURCE_STATE_INIT."'")
	    ->orderBy("rand()")
	    ->limit(HOT_PEOPLE_NUM)
	    ->fetchAll();
  }
}
?>
